﻿using System;
using System.Web.Mvc;
using KPIS.GERP.Models.HRM;
using KPIS.GERP.Models.SYS;
using KPIS.GERP.Models.SYS.ViewModel;
using KPIS.GERP.WEB.GIMS.Class;
using System.Linq;
using KPIS.GERP.WEB.GIMS.SysApprovalService;
using KPIS.GERP.WEB.GIMS.EmployeeService;
using KPIS.GERP.WEB.GIMS.UserService;

namespace KPIS.GERP.WEB.GIMS.Controllers
{
    // [AccessDeniedAuthorize]
    public class AskForApprovalController : Controller
    {
		public ActionResult Index()
		{
            //using (var sysApprovalService = new SysApprovalServiceClient())
            //{
            //    var obj = sysApprovalService.SelectApprovalTasks(GimsMembership.CurrentEmpId).OrderByDescending(t => t.ApprovalTaskId);
            //    ViewBag.ruleApproveTypeList = sysApprovalService.SelectApproveProcess(null);
            //    return View(obj);
            //}
		    return View();
		}

        [HttpPost, ValidateAntiForgeryToken]
        public ActionResult CreateAskApproval(string requestTitle, int refId, string refCode,
            int applyToEmpId, int appPrcGrpId = 0, int appPrcId = 0, string confirmAs = "P", 
            string approveAs = "A", string remark = "")
        {
            //var model = new CreateApprovalTaskVM();
            //model.ApproveProcessEnum = approveProcessEnum;
            //model.RequestTitle = model.ApproveProcessName + ":" + requestTitle;
            //model.ApplyToEmpId = applyToEmpId;
            //model.CreateByEmpId = GimsMembership.CurrentEmpId;
            //model.RefId = refId;
            //model.RefCode = refCode;
            //model.ConfirmAs = confirmAs;
            //model.ApproveAs = approveAs;
            //model.Amount = amount;
            if (appPrcGrpId == 0)
            {
                var approveProcess = new SysApprovalServiceClient()
                    .SelectApproveProcess(0).FirstOrDefault(o => o.AppPrcId == appPrcId);
                if (approveProcess != null)
                {
                    appPrcGrpId = approveProcess.AppPrcGrpId;
                }
            }

            decimal requestAmount = new IcmMasterService.IcmMasterServiceClient()
                .GetRequestAmount(appPrcGrpId, refId) ?? 0;

            var model = new CreateTaskVM();
            model.Title = requestTitle;
            model.ApplyToEmpId = applyToEmpId;
            model.CreateByEmpId = GimsMembership.CurrentEmpId;
            model.RefId = refId;
            model.RefCode = refCode;
            model.ConfirmAs = confirmAs;
            model.ApproveAs = approveAs;
            model.Amount = requestAmount;
            model.Remark = remark;
            model.AppPrcGrpId = appPrcGrpId;
            model.AppPrcId = appPrcId;
            ApproveProcessMapping mappingMatch = null;
            if(model.AppPrcId != 0)
            {
                model.AppPrcId = model.AppPrcId;
            } else
            {
                var cal = new CalAppPrcIdVm();
                cal.Amount = model.Amount;
                cal.AppPrcGrpId = model.AppPrcGrpId;
                cal.AppPrcId = model.AppPrcId;
                cal.ApproveProcessMapping = model.Mapping;
                cal.CalculatedBaseOnEmpId = model.CreateByEmpId;
                cal.CalculatedOn = DateTime.Now;
                cal.Reasons = null;
                cal.RefId = null; 
                model.AppPrcId = new SysApprovalServiceClient().FindAppPrcId(cal).AppPrcId;
                            
                if(model.AppPrcId == 0)
                {
                    throw new Exception(string.Format("ไม่พบประเภทคำขอที่ต้องการภายใต้กลุ่ม [{0}]", model.AppPrcGrpId));
                }
            }

            using(var employeeService = new EmployeeServiceClient())
            {
                model.ApplyToEmployee = employeeService.Select(new Employee{EmpId = model.ApplyToEmpId}, new []{"JobSite"}, true).FirstOrDefault();
                model.CreateByEmployee = employeeService.Select(new Employee{EmpId = model.CreateByEmpId}, new []{"JobSite"}, true).FirstOrDefault();
            }

            ViewBag.mappingMatch = mappingMatch;
            return View(model);
        }

        [HttpPost, ValidateAntiForgeryToken]
        public ActionResult SendAskApproval(CreateTaskVM model)
        {
            // recalculate request amount
            if (model.AppPrcGrpId == 0)
            {
                var approveProcess = new SysApprovalServiceClient()
                    .SelectApproveProcess(0)
                    .FirstOrDefault(o => o.AppPrcId == model.AppPrcId);
                if (approveProcess != null)
                {
                    model.AppPrcGrpId = approveProcess.AppPrcGrpId;
                }
            }

            decimal requestAmount = new IcmMasterService.IcmMasterServiceClient()
                .GetRequestAmount(model.AppPrcGrpId, model.RefId) ?? 0;
            model.Amount = requestAmount;

            // create new task.
            using (var sysApprovalService = new SysApprovalServiceClient())
            {
                model = sysApprovalService.CreateTask(model);
                Session["CreateTaskVM"] = model;
                return RedirectToAction("SendAskApproval");
            }
		}

        [ActionName("SendAskApproval")]
        public ActionResult SendAskApproval2()
        {
            CreateTaskVM model = Session["CreateTaskVM"] as CreateTaskVM;
            if(model == null)
            {
                return RedirectToAction("Index", "Home");
            }
            return View("SendAskApproval", model);
        }
    }
}
